var express = require('express');
var router = express.Router();
const uploadFiles = require('../utils/fileUpload.js');  // 引入配置好的图片上传方法
const {addUsers , getUsers,deleteUsers,login} = require('../controllers/usersControllers')



router.post('/addUsers',async function (req ,res ,next) {
  // 图片上传将用户本地的图片复制到服务器当中
  const upload = uploadFiles();
   upload (req,res, async (err) => {
    if(err) {
      console.log('图片上传失败', err);
  } else {
      console.log('图片上传成功');
        //  获取图片上传成功的图片信息，以及其他新增数据
  // 拼接图片的地址
const avatar ='http://localhost:3000/images/'+req.files[0].filename;
//  获取其他常规数据
   const data = await addUsers({...req.body , avatar})
   res.send(data)
  }
   })


})

router.get('/getUsers',async function (req,res,next) {

 const data = await getUsers()
  res.send(data)
})

router.post('/deleteUsers',async function (req,res,next) {

  const data = await deleteUsers(req.body)
   res.send(data)
 })

 router.post('/login',async function (req,res,next) {
console.log(req.body);
  const data = await login(req.body)
   res.send(data)
 })


//解码token
const jwt = require('jsonwebtoken');
router.get('/getUserInfo', async function(req, res) {
    // 获取请求头的 token
    const tokenBearer = req.get('Authorization');
    const token = tokenBearer.split(" ")[1];
    // 对 token 解码，获取 token 中的用户信息
    const { user } = jwt.verify(token, 'hello');
    res.send({
        code: 1,
        message: '用户信息获取成功',
        data: user
    })
})




module.exports = router;
